<template>
  <view>
    <view style="height: 15vh;"></view>
    <view class="mask-avatar">
      <button
        open-type="chooseAvatar"
        @chooseavatar="handlebindchooseavatar"
        style="width: 160rpx; height: 160rpx; opacity: 0"
      >完善资料</button>
    </view>
    <up-row type="flex" justify="center">
      <image style="width: 160rpx; height: 160rpx;" mode="aspectFill" :src="model1.avatar"></image>
    </up-row>

    <up-form :model="model1" ref="formRef" :rules="rules" labelWidth="100px" class="u-p-t-40">
      <up-form-item
          label="昵称"
          prop="nickName"
          class="u-border-bottom  u-m-l-40 u-m-r-40"
      >
        <up-input
          v-model="model1.nickName"
          disabledColor="#ffffff"
          placeholder="请填写"
          border="none"
          type="nickname"
        ></up-input>
      </up-form-item>
      <up-form-item
          label="手机号"
          prop="phone"
          class="u-border-bottom  u-m-l-40 u-m-r-40"
      >
        <up-input
          v-model="model1.phone"
          disabledColor="#ffffff"
          placeholder="请填写"
          border="none"
        ></up-input>
      </up-form-item>
    </up-form>

    <view class="footer u-p-30">
      <up-button :color="$u.color.mainColor" @click="save" size="large">保存</up-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { common } from '@/utils/api'
import { onShow, onHide,onLoad } from "@dcloudio/uni-app"
import cache from '@/utils/cached'
import { cos } from '@/utils/cos.js'

const userInfo = cache.getUserInfo() || {};
const model1 = ref({
  nickName: '',
  phone: '',
  avatar: ''
})
const rules = ref({
  nickName: [
    {
      required: true,
      message: '请输入用户昵称',
      trigger: ['blur', 'change']
    }
  ],
  phone: [
    {
      required: true,
      message: '请填写联系电话',
      trigger: ['blur', 'change']
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式错误',
      trigger: ['blur', 'change']
    }
  ]
})

onLoad((options) => {
  model1.value.avatar = userInfo.avatar || 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132'
  model1.value.nickName = userInfo.nickName
  model1.value.phone = userInfo.phone
})
const handlebindchooseavatar = (e) => {
  const { avatarUrl } = e.detail;
  console.log('临时路径：' + avatarUrl);

  // 本地临时路径转为永久路径
  uni.saveFile({
    tempFilePath: avatarUrl,
    success: async (res) => {
      console.log('永久路径：' + res.savedFilePath);
      const savedFilePath = res.savedFilePath;

      const newUrl = await uploadFilePromise(savedFilePath)
      model1.value.avatar = newUrl
    }
  });
};

const formRef = ref()
const save = async () => {
  let status = await formRef.value.validate()
  if (!status) return;

  const params = {
    ...model1.value,
    avatar: model1.value.avatar
  }
  const { code } = await common.complete(params)
  const userInfo = {
    avatar: model1.value.avatar,
    nickName: model1.value.nickName,
    phone: model1.value.phone
  }
  cache.setUserInfo(userInfo)
  uni.navigateBack({})
}

const uploadFilePromise = (filePath) => {
  return new Promise((resolve, reject) => {
    cos.uploadFile({
      Bucket: 'cloudmall-1258631430', // 填入您自己的存储桶，必须字段
      Region: 'ap-chengdu',  // 存储桶所在地域，例如ap-beijing，必须字段
      Key: 'miniprogram/user/' + 'avatar_'+ +new Date() +'.jpg',  // 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段
      FilePath: filePath, // 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象
      SliceSize: 1024 * 1024 * 5,     // 触发分块上传的阈值，超过5MB使用分块上传，非必须
      onTaskReady: function(taskId) {  // 非必须
        console.log(taskId);
      },
      onProgress: function (progressData) { // 非必须
        console.log(JSON.stringify(progressData));
      },
      // 支持自定义headers 非必须
      Headers: {
        'x-cos-meta-test': 123
      },
    }, function(err, data) {
      if (err) {
        console.log('上传失败', err);
      } else {
        console.log('上传成功', data);
        let newUrl = data.Location.replace('cloudmall-1258631430.cos.ap-chengdu.myqcloud.com/', 'https://mall-image.linkland.cc/')

        resolve(newUrl)
      }
    });
  })
}
</script>

<style lang="scss" scoped>
.mask-avatar {
  position: absolute;
  left: 50%;
  top: 15vh;
  width: 160rpx;
  height: 160rpx;
  transform: translate(-50%, 0%);
  z-index: 999;
}

.footer {
  position: fixed;
  left: 0px;
  bottom: 0px;
  z-index: 999;
  width: 100%;
  box-sizing: border-box;
}
</style>